﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using CWB.Common.Constant;
using CWB.Common.Logging;
using CWB.Web.DB;
using CWB.Web.Models.Configuration;
using CWB.Web.MVC.BaseController;
using CWB.Web.MVC.Filters;
using CWB.Common.Utilities;
using CWB.WebSite.Models.Agent;
using System.Linq;

namespace CWB.WebSite.Controllers
{
    public class AgentController : MultiCultureBaseController
    {
        private static readonly ISysLog Log = SysLog.GetLogger(typeof(AgentController));

        public AgentController(LanguageInfo languageInfo)
            : base(languageInfo)
        {
            ControllerPermision = Permission.Private;
        }

        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public ActionResult Index(int? id)
        {
            int iUplinesn = Convert.ToInt16(id);
            if (iUplinesn == 0 && sessionData.trading.loginType == LoginType.Agent)
            {
                iUplinesn = sessionData.trading.sn;
            }
            ViewData["uplinesn"] = iUplinesn;
            return View("~/Views/Agent/AgentIndex.aspx");
        }

        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public ActionResult Member(int? id)
        {
            int iUplinesn = Convert.ToInt16(id);
            if (iUplinesn == 0 && sessionData.trading.loginType == LoginType.Agent)
            {
                iUplinesn = sessionData.trading.sn;
            }
            ViewData["uplinesn"] = iUplinesn;
            ViewData["position"] = 3;
            return View("~/Views/Agent/AgentIndex.aspx");
        }

        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public ActionResult Create(int? id)
        {
            int iUplinesn = Convert.ToInt16(id);
            if (iUplinesn ==0 && sessionData.trading.loginType == LoginType.Agent)
            {
                iUplinesn = sessionData.trading.sn;
            }
            AgentUpdateModel model = getAGUpdateModel(0, iUplinesn);
            ViewData.Model = model;
            return View("~/Views/Agent/AgentCreate.aspx");
        }

        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public ActionResult BoUpdateAgent(int id)
        {
            AgentUpdateModel model = new AgentUpdateModel();
            try
            {
                DbTableAgent odb = new DbTableAgent();
                DbTableProduct otp = new DbTableProduct();
                List<DbModuleProd> allProd = otp.getSupportedProdItems(id);

                //Get possess range
                model.Agent = odb.getAgentbySn(id);
                model.PossessRange = odb.getRangeBySN(id, model.Agent.uplinesn);
                model.ProdItems = getAgentUpdateProdItems(allProd, model.Agent.ProdItems);
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
                model.errmsg = Localization.TrandlateMessage(Err.ProductIsNotExisting);
            }
            ViewData.Model = model;
            return View("~/Views/Agent/AgentUpdate.aspx");
        }

        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public ActionResult ChPwdAgent(int id)
        {
            try
            {
                DbTableAgent odb = new DbTableAgent();
                ViewData["AgentSN"] = id;
                ViewData["AgentLoginId"] = odb.getAgentbySn(id).Loginid;
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
                ViewData["error"] = "This agent information not found.";
            }
            return View("~/Views/Agent/AgentChangePwd.aspx");
        }

        [NoClientCacheFilter]
        [PermissionFilterAttvibute(loginType = LoginType.Agent)]
        public ActionResult AGCreate()
        {
            AgentUpdateModel model = getAGUpdateModel(9999999, 9999999);
            ViewData.Model = model;
            return View("~/Views/Agent/AgentCreate.aspx");
        }

        [NoClientCacheFilter]
        [PermissionFilterAttvibute(loginType = LoginType.Bo)]
        public ActionResult BoCreateAG(int id)
        {
            return CreateAgent(id);
        }

        private ActionResult CreateAgent(int parentAgentSN)
        {
            AgentUpdateModel model = new AgentUpdateModel();
            DbTableAgent odb = new DbTableAgent();
            DbTableProduct otp = new DbTableProduct();
            List<DbModuleProd> allProd = otp.getSupportedProdItems(parentAgentSN);
            try
            {
                //Get possess range
                model.PossessRange = odb.getRangeBySN(0, parentAgentSN);
                model.Agent = odb.getAgentbySn(0);
                model.ProdItems = getAgentUpdateProdItems(allProd, model.Agent.ProdItems);
                //Assign create necessary information.
                model.Agent.uplinesn = parentAgentSN;
            
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
                model.errmsg = ex.Message;
            }

            ViewData.Model = model;
            return View("~/Views/Agent/AgentCreate.aspx");
        }

        private List<AgentUpdateProdItemModel> getAgentUpdateProdItems(List<DbModuleProd> allProd, List<AgentProdItem> ProdItems)
        {
            List<AgentUpdateProdItemModel> viewPordItem =
                (from L1 in allProd
                 join L2 in ProdItems on L1.sn equals L2.prodSN into temptable
                 from L2 in temptable.DefaultIfEmpty(new AgentProdItem() { price = 0 })
                 select new AgentUpdateProdItemModel()
                 {
                     price = L2.price,
                     fee = L1.fee,
                     prodName = L1.prodName,
                     prodid = L1.prodid,
                     sn = L1.sn,
                     unit = L1.unit,
                     unitvalue = L1.unitvalue
                 }).ToList();
            return viewPordItem;
        }

        private AgentUpdateModel getAGUpdateModel(int CurrentSN, int ParentSN)
        {
            AgentUpdateModel model = new AgentUpdateModel();
            try
            {
                DbTableAgent odb = new DbTableAgent();
                DbTableProduct otp = new DbTableProduct();
                List<DbModuleProd> allProd = otp.getSupportedProdItems(ParentSN);
                //Get possess range
                model.PossessRange = odb.getRangeBySN(CurrentSN, ParentSN);
                model.Agent = odb.getAgentbySn(CurrentSN);
                if (CurrentSN == 0 && ParentSN > 0)
                {
                    model.Agent.uplinesn = ParentSN;
                }
                model.ProdItems = getAgentUpdateProdItems(allProd, model.Agent.ProdItems);

                //Get DownlineRange, just only apply to Agent.
                if (sessionData.trading.loginType != LoginType.Bo)
                {
                    model.parentLoginid = odb.getAgentbySn(ParentSN).Loginid;
                    model.DownLineList = odb.getDownLineRange(ParentSN);
                }

            }
            catch (Exception ex)
            {
                Log.Exception(ex);
                model.errmsg = Localization.TrandlateMessage(Err.ProductIsNotExisting);
            }
            return model;
        }

    }
}
